package cn.wit.summit.chwan.ui.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.aigestudio.wheelpicker.WheelPicker;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.core.ImagePipeline;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.models.dto.CfgExplainBean;
import cn.wit.summit.chwan.models.response.ChangeIconResponse;
import cn.wit.summit.chwan.models.response.PicCollectionTypeListResponse;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.ui.base.MyActivity;
import cn.wit.summit.chwan.ui.base.MyApplication;
import cn.wit.summit.chwan.utils.AccountBean;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.FileUtil;
import cn.wit.summit.chwan.utils.FileUtils;
import cn.wit.summit.chwan.utils.IntentUtil;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.utils.PhotoSelectUtils;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.utils.UtilsMy;
import cn.wit.summit.chwan.widgets.CurrencyPromptDialog;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * Created by Alan on 2018/7/16.
 */

public class UpLoadImageActivity extends MyActivity {

    @Bind(R.id.imageContentEt)
    EditText imageContentEt;
    @Bind(R.id.bottomRuleLl)
    LinearLayout bottomRuleLl;
    @Bind(R.id.chenckMoreRuleTx)
    TextView chenckMoreRuleTx;
    @Bind(R.id.imageSelectedIv)
    SimpleDraweeView imageSelectedIv;
    @Bind(R.id.imageTypeNameTv)
    TextView imageTypeNameTv;
    @Bind(R.id.imageRootRl)
    LinearLayout imageRootRl;
    @Bind(R.id.wheelPicker)
    WheelPicker wheelPicker;
    @Bind(R.id.wheelPickerRl)
    RelativeLayout wheelPickerRl;
    @Bind(R.id.rlBottom)
    RelativeLayout rlBottom;

    private TextView mBarRightTx;

    private String filePath;
    private String gameId;
    private int mPosition;
    private List<PicCollectionTypeListResponse.PicListBean> mData;

    private RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private ApiUtil api;

    private String upImageDec;
    private String upImageTypeId;
    private String upImageTypeName;

    private List<String> lists = new ArrayList<>();
    private CfgExplainBean listRule;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_image);
        ButterKnife.bind(this);

        retrofitManager = RetrofitManager.getInstance(mContext);
        retrofit = retrofitManager.getRetrofit();
        api = retrofit.create(ApiUtil.class);

        // 1、创建PhotoSelectUtils（一个Activity对应一个PhotoSelectUtils）
        mPhotoSelectUtils = new PhotoSelectUtils(this
                , new PhotoSelectUtils.PhotoSelectListener() {
            @Override
            public void onFinish(File outputFile, Uri outputUri) {
                // 4、当拍照或从图库选取图片成功后回调
                mUpFile = outputFile;
                startPhotoImg(outputUri);
            }
        }, false);//true裁剪，false不裁剪

        showRule();
        initData();
        initView();
    }

    private void initView() {
        setBarTitleTx(R.string.pic_list_title);
        mBarRightTx = setBarRightTx(getResources().getString(R.string.image_right_tx));
        mBarRightTx.setBackgroundResource(R.drawable.selector_commit_bg);
        mBarRightTx.setTextColor(Color.parseColor("#bfffffff"));
        mBarRightTx.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.wdp28));
        mBarRightTx.setEnabled(false);
        mBarRightTx.setOnClickListener(null);
        imageContentEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String str = s.toString().trim();
                if (StringUtils.isEmpty(str) || str.length() > 100) {
                    mBarRightTx.setTextColor(Color.parseColor("#bfffffff"));
                    mBarRightTx.setEnabled(false);
                    mBarRightTx.setOnClickListener(null);
                } else {
                    mBarRightTx.setTextColor(Color.parseColor("#43BEFE"));
                    mBarRightTx.setEnabled(true);
                    mBarRightTx.setOnClickListener(new TopRightClickListener());
                }
            }
        });
    }

    private void initData() {
        filePath = getIntent().getStringExtra("filePath");
        if (StringUtils.isEmpty(filePath)){
            finish();
            return;
        }
        mUpFile = new File(filePath);
        if (mUpFile==null || !mUpFile.exists()){
            finish();
            return;
        }
        startPhotoImg(Uri.fromFile(mUpFile));

        gameId = getIntent().getStringExtra("gameId");
        mPosition = getIntent().getIntExtra("mPosition", 0);
        mData = (List<PicCollectionTypeListResponse.PicListBean>) getIntent().getSerializableExtra("mData");//获取list方

        for (int i = 0; mData != null && i < mData.size(); i++) {
            lists.add(mData.get(i).getTitle());
        }
        upImageTypeId = mData.get(mPosition).getId();
        upImageTypeName = mData.get(mPosition).getTitle();
        imageTypeNameTv.setText(upImageTypeName);
        wheelPicker.setData(lists);
        wheelPicker.setCyclic(false);
        wheelPicker.setSelectedItemPosition(mPosition);
        wheelPicker.setOnItemSelectedListener(new WheelPicker.OnItemSelectedListener() {
            @Override
            public void onItemSelected(WheelPicker picker, Object data, int position) {
                upImageTypeId = mData.get(position).getId();
                upImageTypeName = mData.get(position).getTitle();
            }
        });
    }

    private void showRule() {
        listRule = MyApplication.arrayUploadExplain;
        if (listRule==null || StringUtils.isEmpty(listRule.getExplain())) {
            rlBottom.setVisibility(View.GONE);
            return;
        }

        rlBottom.setVisibility(View.VISIBLE);
        bottomRuleLl.removeAllViews();
//        String[] text = getResources().getStringArray(R.array.create_comment_rule_list);

        String[] text = listRule.getExplain().split("<br />");
        for (int i = 0; i < text.length; i++) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_rule_view, null, false);
            TextView itemRuleOneTx = view.findViewById(R.id.itemRuleOneTx);
            TextView itemRuleTwoTx = view.findViewById(R.id.itemRuleTwoTx);

            itemRuleOneTx.setText((i + 1) + "、");

            String temp = text[i];
            if (temp.contains("给予") && temp.contains("元")) {
                int numS = temp.indexOf("给予");
                int numE = temp.indexOf("元");

                SpannableString spannableString = new SpannableString(temp);
                //设置颜色
                spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#000000")), numS + 2, numE + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                //设置字体，BOLD为粗体
                spannableString.setSpan(new StyleSpan(Typeface.BOLD), numS + 2, numE + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                itemRuleTwoTx.setText(spannableString);
            } else {
                itemRuleTwoTx.setText(temp);
            }
            if (i > 0) {
                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                params.topMargin = (int) getResources().getDimension(R.dimen.wdp17);
                view.setLayoutParams(params);
            }

            bottomRuleLl.addView(view);
        }
    }

    @OnClick({R.id.imageSelectedIv, R.id.imageRootRl, R.id.wheelPickerTopLeftTx, R.id.wheelPickerTopRightTx
            , R.id.chenckMoreRuleTx})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.imageSelectedIv:
                ChangIcon();
                break;
            case R.id.imageRootRl:
                showSelectDialog();
//                wheelPickerRl.setVisibility(View.VISIBLE);
                break;
            case R.id.wheelPickerTopLeftTx:
                wheelPickerRl.setVisibility(View.GONE);
                break;
            case R.id.wheelPickerTopRightTx:
                wheelPickerRl.setVisibility(View.GONE);
                imageTypeNameTv.setText(upImageTypeName);
                break;
            case R.id.chenckMoreRuleTx:
                if (listRule!=null && !StringUtils.isEmpty(listRule.getUrl())) {
                    IntentUtil.getInstance().goShareWebActivity(mContext, listRule.getUrl());
                }
                break;
        }
    }

    private Dialog selectDialog;
    private void showSelectDialog(){
        selectDialog = new Dialog(mContext, R.style.floate_dialog);
        selectDialog.setContentView(R.layout.dialog_select_type_choose);
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        Window dlgwin = selectDialog.getWindow();
        WindowManager.LayoutParams lp = dlgwin.getAttributes();
        dlgwin.setGravity(Gravity.BOTTOM);
        lp.width = display.getWidth(); //设置宽度
        selectDialog.getWindow().setAttributes(lp);
        LinearLayout selectListLl = selectDialog.findViewById(R.id.selectListLl);
        TextView selectCancelTv = selectDialog.findViewById(R.id.selectCancelTv);

        selectListLl.removeAllViews();
        for (int i = 0; mData != null && i < mData.size(); i++) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_select_item_type_choose, null);
            TextView textView = view.findViewById(R.id.selectItemTx);
            TextView selectItemLineTx = view.findViewById(R.id.selectItemLineTx);

            if (i!=(mData.size()-1))
                selectItemLineTx.setVisibility(View.VISIBLE);
            textView.setText(mData.get(i).getTitle());
            textView.setTag(i);
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    TextView temp = (TextView) v;
                    int num = (Integer) temp.getTag();
                    upImageTypeId = mData.get(num).getId();
                    upImageTypeName = mData.get(num).getTitle();
                    selectDialog.dismiss();
                    imageTypeNameTv.setText(upImageTypeName);
                }
            });
            selectListLl.addView(view);
        }
        selectCancelTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectDialog.dismiss();
            }
        });
        selectDialog.show();
    }

    private Dialog mPicChsDialog;
    private File mUpFile;

    private void ChangIcon() {
        mPicChsDialog = new Dialog(mContext, R.style.floate_dialog);
        mPicChsDialog.setContentView(R.layout.dialog_pic_choose);
        WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
        Window dlgwin = mPicChsDialog.getWindow();
        WindowManager.LayoutParams lp = dlgwin.getAttributes();
        dlgwin.setGravity(Gravity.BOTTOM);
        lp.width = display.getWidth(); //设置宽度
        mPicChsDialog.getWindow().setAttributes(lp);
        TextView camera = (TextView) mPicChsDialog.findViewById(R.id.chos_camera);
        TextView picLib = (TextView) mPicChsDialog.findViewById(R.id.pic_lib);
        TextView cancel = (TextView) mPicChsDialog.findViewById(R.id.btn_cancel);
        camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPicChsDialog.dismiss();
                PermissionGen.with(mAty)
                        .addRequestCode(PhotoSelectUtils.REQ_TAKE_PHOTO)
                        .permissions(Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.CAMERA
                        ).request();
            }
        });

        picLib.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPicChsDialog.dismiss();
                PermissionGen.needPermission(mAty,
                        PhotoSelectUtils.REQ_SELECT_PHOTO,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE}
                );
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPicChsDialog.dismiss();
            }
        });
        mPicChsDialog.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 2、在Activity中的onActivityResult()方法里与LQRPhotoSelectUtils关联
        mPhotoSelectUtils.attachToActivityForResult(requestCode, resultCode, data);
    }

    private void startPhotoImg(Uri uri) {
        ImagePipeline imagePipeline = Fresco.getImagePipeline();
        imagePipeline.evictFromMemoryCache(uri);
        imagePipeline.evictFromDiskCache(uri);
        imagePipeline.evictFromCache(uri);

        DraweeController controller = Fresco.newDraweeControllerBuilder()
                .setUri(uri)
                .setAutoPlayAnimations(true)
                .build();
        imageSelectedIv.setController(controller);
    }

    private String path = MyApplication.getMyApplication().getAppRootPath() + FileUtils.SDPATH_IMAGE;

    private class TopRightClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            AccountBean accountBean = AccountUtil.getInstance().getAccountData();
            if (accountBean == null) {//未登录
                IntentUtil.getInstance().goLoginActivity(UpLoadImageActivity.this);
                return;
            }

            upImageDec = imageContentEt.getText().toString().trim();
            if (StringUtils.isEmpty(upImageDec)) {
                showToast(getResources().getString(R.string.wran_toast));
                return;
            }
            if (mUpFile==null || !mUpFile.exists()) {
                showToast(getResources().getString(R.string.wran_toast_2));
                return;
            }

            Luban.with(mAty).load(mUpFile).ignoreBy(100).setTargetDir(getPath())
                    .filter(new CompressionPredicate() {
                        @Override
                        public boolean apply(String path) {
                            return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
                        }
                    })
                    .setCompressListener(new OnCompressListener() {
                        @Override
                        public void onStart() {
                            // TODO 压缩开始前调用，可以在方法内启动 loading UI
                            showLoading("正在上传前压缩", false);
                        }

                        @Override
                        public void onSuccess(File file) {
                            // TODO 压缩成功后调用，返回压缩后的图片文件
                            mUpFile = file;
                            ReShowLoading("正在上传");
                            toUpImage();
                        }

                        @Override
                        public void onError(Throwable e) {
                            // TODO 当压缩过程出现问题时调用
                            cancelLoading();
                            showToast("压缩失败！");
                        }
                    }).launch();
        }
    }

    private String getPath() {
        File f = new File(path);
        if (!f.exists()) {
            f.mkdirs();
        }
        File[] fs = f.listFiles();
        if (fs != null) {
            for (File fi : fs) {
                if (fi.exists() && fi.isFile() && fi.getName().endsWith(".jpg")) {
                    UtilsMy.delete(fi);
                }
            }
        }
        return f.getPath();
    }

    private void toUpImage() {
        //上传头像
        if (NetWorkUtils.isNetworkConnected(mContext)) {
            MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);//表单类型
            RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), mUpFile);
            builder.addFormDataPart("files", mUpFile.getName(), imageBody);//imgfile 后台接收图片流的参数名

            MultipartBody.Part part = builder.build().part(0);
            String token = MyApplication.accountBean.getToken();
            if (token == null) {
                showToast("Token为空");
                return;
            }
            RequestBody tokenBody = RequestBody.create(MediaType.parse("form-data"), token);
            RequestBody decBody = RequestBody.create(MediaType.parse("form-data"), upImageDec);
            api.addPicToImage(part, MyApplication.accountBean.getUid(), tokenBody, Long.valueOf(gameId), Long.valueOf(upImageTypeId), decBody)
                    .enqueue(new Callback<ChangeIconResponse>() {
                        @Override
                        public void onResponse(Call<ChangeIconResponse> call, Response<ChangeIconResponse> response) {
                            if (call.isCanceled()) return;
                            ChangeIconResponse model = response.body();
                            if (model.getCode() == 600) {
                                mUpFile = null;
                                showSuccDialog();
                            } else {
                                cancelLoading();
                                showToast("上传失败，请重试！");
                            }
                        }

                        @Override
                        public void onFailure(Call<ChangeIconResponse> call, Throwable t) {
                            if (call.isCanceled()) return;
                            cancelLoading();
                            if (t.getMessage().contains("timeout")) {
                                showToast("上传超时，请重试！");
                                return;
                            }
                            showToast("上传失败，请重试！");
                        }
                    });
        } else {
            cancelLoading();
            showToast("网络连接失败，再试试吧~");
        }
    }

    private void showSuccDialog() {
        final CurrencyPromptDialog dialog = new CurrencyPromptDialog(mContext);
        dialog.show();
        dialog.setTitle("发布成功");
        dialog.setMsg("您上传的照片已发布成功，我们会尽快对照片进行审核，感谢支持！");
        dialog.setCancelIvGone();
        dialog.setCancleBtn("我知道了", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                finish();
            }
        });
    }

    private PhotoSelectUtils mPhotoSelectUtils;
    @PermissionSuccess(requestCode = PhotoSelectUtils.REQ_TAKE_PHOTO)
    private void takePhoto() {
        mPhotoSelectUtils.takePhoto();
    }

    @PermissionSuccess(requestCode = PhotoSelectUtils.REQ_SELECT_PHOTO)
    private void selectPhoto() {
        mPhotoSelectUtils.selectPhoto();
    }

    @PermissionFail(requestCode = PhotoSelectUtils.REQ_TAKE_PHOTO)
    private void showTip1() {
        //        Toast.makeText(getApplicationContext(), "不给我权限是吧，那就别玩了", Toast.LENGTH_SHORT).show();
        showDialog();
    }

    @PermissionFail(requestCode = PhotoSelectUtils.REQ_SELECT_PHOTO)
    private void showTip2() {
        //        Toast.makeText(getApplicationContext(), "不给我权限是吧，那就别玩了", Toast.LENGTH_SHORT).show();
        showDialog();
    }

    public void showDialog() {
        //创建对话框创建器
        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
        //设置对话框显示小图标
        builder.setIcon(android.R.drawable.ic_dialog_alert);
        //设置标题
        builder.setTitle("权限申请");
        //设置正文
        builder.setMessage("在设置-应用-虎嗅-权限 中开启相机、存储权限，才能正常使用拍照或图片选择功能");

        //添加确定按钮点击事件
        builder.setPositiveButton("去设置", new DialogInterface.OnClickListener() {//点击完确定后，触发这个事件

            @Override
            public void onClick(DialogInterface dialog, int which) {
                //这里用来跳到手机设置页，方便用户开启权限
                Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS);
                intent.setData(Uri.parse("package:" + mAty.getPackageName()));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });

        //添加取消按钮点击事件
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });

        //使用构建器创建出对话框对象
        android.support.v7.app.AlertDialog dialog = builder.create();
        dialog.show();//显示对话框
    }
}
